﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class game : MonoBehaviour {
    public float size, r_starty, r_bannery;

    private float startx, starty, bannery;
    private int[,] board;
    private int empty, turn, winner;

    void Start() {
        startx = (Screen.width - 3 * size) * 0.5f;
        starty = Screen.height * r_starty;
        bannery = Screen.height * r_bannery;
        board = new int[3, 3];
        Init();
    }
    void Update() {

    }
    void Init() {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                board[i, j] = 0;
            }
        }
        empty = 9;
        turn = -1;
        winner = 0;
    }
    void OnGUI() {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                if (board[i, j] == 0) {
                    if (GUI.Button(new Rect(startx + i * size, starty + j * size, size, size), "")) {
                        board[i, j] = turn;
                        --empty;
                        turn = -turn;
                        winner = GameOver();
                    }
                }
                else {
                    string symbol = board[i, j] == -1 ? "O" : "X";
                    GUI.Button(new Rect(startx + i * size, starty + j * size, size, size), symbol);
                }
            }
        }
        if (winner != 0 || empty == 0) {
            const float label_width = 200.0f;
            const float label_height = 50.0f;
            float labelx = (Screen.width - label_width) * 0.5f;
            string result = "";
            if (empty == 0) {
                result = "DRAW!";
            }
            else {
                result = (winner == -1 ? "O" : "X") + " WINS!";
            }
            GUI.Label(new Rect(labelx, bannery, label_width, label_height), result);
            const float button_width = 100.0f;
            const float button_height = 20.0f;
            float button_x = (Screen.width - button_width) * 0.5f;
            if (GUI.Button(new Rect(button_x, bannery + label_height + 5.0f, button_width, button_height), "RESTART")) {
                Init();
            }
        }
    }
    int GameOver() {
        int[] cnt = new int[8];
        for (int i = 0; i < 3; ++i) {
            for (int j = 0;j < 3; ++j) {
                cnt[i] += board[i, j];
                cnt[3 + j] += board[i, j];
                if (i == j) {
                    cnt[6] += board[i, j];
                }
                if (i + j == 2) {
                    cnt[7] += board[i, j];
                }
            }
        }
        for (int i = 0; i < 8; ++i) {
            if (cnt[i] == -3) {
                return -1;
            }
            if (cnt[i] == 3) {
                return 1;
            }
        }
        return 0;
    }
}
